import axios from 'axios';

const instance = axios.create({
  baseURL: "http://localhost:8090/api/v1/payments",
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

instance.interceptors.request.use(
  config => {
    console.log(`Sending request to: ${config.baseURL}${config.url}`);
    return config;
  },
  error => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    console.log('Received response:', {
      url: response.config.url,
      status: response.status,
      data: response.data
    });
    return response.data;
  },
  error => {
    const errorInfo = {
      url: error.config?.url,
      status: error.response?.status,
      message: error.message,
      responseData: error.response?.data
    };
    console.error('API Error:', errorInfo);
    
    if (error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求参数错误';
          break;
        case 401:
          error.message = '未授权，请登录';
          break;
        case 403:
          error.message = '拒绝访问';
          break;
        case 404:
          error.message = `请求地址出错: ${error.config.url}`;
          break;
        case 500:
          error.message = '服务器内部错误';
          break;
        default:
          error.message = `连接错误: ${error.response.status}`;
      }
    } else if (error.request) {
      error.message = '网络连接异常，请检查网络';
    }
    
    return Promise.reject(error);
  }
);

const PaymentService = {
  getFrontendData: async () => {
    try {
      const response = await instance.get('/frontend-data');
      return response;
    } catch (error) {
      console.error('Failed to get frontend data:', error);
      throw error;
    }
  },

  generateMockData: async (count) => {
    try {
      const response = await instance.post(`/generate/${count}`);
      return response;
    } catch (error) {
      console.error('Failed to generate mock data:', error);
      throw error;
    }
  },

  getFallbackData: () => {
    console.warn('Using fallback data');
    const departments = ['销售部', '技术部', '市场部', '财务部', '人力资源部'];
    
    const personalData = Array.from({ length: 15 }, (_, i) => ({
      key: `emp-${i}`,
      rank: i + 1,
      name: `员工${i + 1}`,
      department: departments[i % departments.length],
      paymentAmount: Math.floor(Math.random() * 100000) + 50000,
      paymentCount: Math.floor(Math.random() * 20) + 1,
      overdueCount: Math.floor(Math.random() * 5),
      invoiceAmount: Math.floor(Math.random() * 80000) + 20000
    }));

    const departmentData = departments.map((dept, i) => ({
      key: `dept-${i}`,
      rank: i + 1,
      name: dept,
      paymentAmount: Math.floor(Math.random() * 500000) + 200000,
      paymentCount: Math.floor(Math.random() * 100) + 20,
      overdueCount: Math.floor(Math.random() * 15),
      invoiceAmount: Math.floor(Math.random() * 400000) + 100000
    }));

    return {
      personalData,
      departmentData: departmentData.sort((a, b) => b.paymentAmount - a.paymentAmount)
    };
  }
};

export default PaymentService;